package com.netty.rpc.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.nio.charset.Charset;

public class RpcClient {

    public <T> T refer(Class<T> clazz){

       return (T)Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] {clazz}, (InvocationHandler) (proxy, method, args) -> {
           try(Socket socket = new Socket("192.168.128.228", 8081);
               ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())){
               outputStream.writeUTF(clazz.getSimpleName());
               outputStream.writeUTF(clazz.getName());
               outputStream.writeUTF(method.getName());
               outputStream.writeObject(method.getParameterTypes());
               outputStream.writeObject(args);
               ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
               return inputStream.readObject();
           }
       });
    }
}
